package net.zoneland.zrdp.biz.validator;

import net.zoneland.zrdp.biz.domain.pojo.form.ApprovePeopleForm;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.*;

/**
 * 获取处理人参数对象字段指定值组合校验.
 *
 * @version v1.0
 */
@Documented
@Constraint(validatedBy = ApprovePeopleFormValidator.class)
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface ApprovePeople {

    String message() default "{javax.validation.constraints.ApprovePeopleForm.message}";

    int min() default 0;

    int max() default Integer.MAX_VALUE;

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

}

/**
 * 获取处理人参数对象字段指定值组合校验实现.
 *
 * @version v1.0
 */
class ApprovePeopleFormValidator implements ConstraintValidator<ApprovePeople, ApprovePeopleForm> {

    /**
     * 重写校验方法.
     * @param approvePeopleForm	获取处理人参数对象.
     * @param context 约束验证器上下文.
     * @return boolean
     **/
    @Override
    public boolean isValid(final ApprovePeopleForm approvePeopleForm, final ConstraintValidatorContext context) {
        switch(approvePeopleForm.getRollback()) {
            case REJECT_NODE:
                return setMessage(
                    context, "当rollback为1时，piid、tiid都不能为空",
                    StringUtils.isNoneBlank(approvePeopleForm.getPiid(), approvePeopleForm.getTiid()));
            case SPLIT_REJECT_NODE:
                return setMessage(
                    context, "当rollback为2时，piid、nodeId都不能为空",
                    StringUtils.isNoneBlank(approvePeopleForm.getPiid(), approvePeopleForm.getNodeId()));
            case NEXT_NODE:
                return setMessage(
                    context, "当rollback为3时，roleId都不能为空",
                    StringUtils.isNotBlank(approvePeopleForm.getRoleId()));
            default:
                return setMessage(
                    context, "当rollback为4、5、6时，approveDept都不能为空",
                    CollectionUtils.isNotEmpty(approvePeopleForm.getApproveDept()));
        }
    }

    /**
     * 设置返回信息.
     * @param context 约束验证器上下文.
     * @param message 返回信息.
     * @param noneBlank 是否通过校验.
     * @return boolean
     **/
    private static boolean setMessage(final ConstraintValidatorContext context,
                                      final String message, final boolean noneBlank) {
        context.disableDefaultConstraintViolation();
        context.buildConstraintViolationWithTemplate(message).addConstraintViolation();
        return noneBlank;
    }
}

